package com.hamu.controller;

import com.hamu.pojo.*;
import com.hamu.service.MediaService;
import com.hamu.utils.AliOssUtil;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/media")
public class MediaController {
    @Autowired
    private MediaService mediaService;

    @PostMapping
    public Result add(@RequestBody @Validated Media media){
        mediaService.add(media);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam @NotNull Integer id) {
        Media media = mediaService.findById(id);
        if (media == null) {
            return Result.error("该媒体文件不存在");
        }
        mediaService.delete(id);
        // Delete the file from AliOSS
        try {
            AliOssUtil.deleteFile(media.getMediaUrl());
        } catch (Exception e) {
            return Result.error("文件删除失败");
        }
        return Result.success();
    }

    @GetMapping("/detail")
    public Result<Media> detail(@NotNull Integer id) {
        Media media = mediaService.findById(id);
        if (media == null) {
            return Result.error("该媒体文件不存在");
        }
        return Result.success(media);
    }

    @GetMapping("/all")
    public Result<PageBean<Media>> list(
            Integer pageNum,
            Integer pageSize
    ) {
        PageBean<Media> pb = mediaService.list(pageNum, pageSize);
        return Result.success(pb);
    }

    @GetMapping("/search")
    public Result<PageBean<Media>> searchMedias(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) String query){
        PageBean<Media> pb = mediaService.searchList(pageNum, pageSize,query);
        return Result.success(pb);
    }

    @PutMapping
    public Result update(@RequestBody @Validated Media media) {
        if (mediaService.findById(media.getId()) == null) {
            return Result.error("该媒体不存在");
        }
        mediaService.update(media);
        return Result.success();
    }


}
